package com.qsmx.store.app.main.mem;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatTextView;
import android.view.View;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qsmx.store.app.R;
import com.qsmx.store.app.R2;
import com.qsmx.store.app.entity.login.LoginEntity;
import com.qsmx.store.app.event.CardReadEvent;
import com.qsmx.store.app.event.CardWriteEvent;
import com.qsmx.store.app.fustion.FustionManager;
import com.qsmx.store.app.http.HttpHelper;
import com.qsmx.store.app.http.HttpUrl;
import com.qsmx.store.app.main.mem.entity.MemGetCardEntity;
import com.qsmx.store.app.main.mem.entity.MemSendCardEntity;
import com.qsmx.store.app.util.CardReadUtil;
import com.qsmx.store.app.util.StringUtil;
import com.qsmx.store.core.delegates.AtmosDelegate;
import com.qsmx.store.core.fusion.FusionCode;
import com.qsmx.store.core.net.callback.IError;
import com.qsmx.store.core.net.callback.IFailure;
import com.qsmx.store.core.net.callback.ISuccess;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.WeakHashMap;

import butterknife.BindView;
import butterknife.OnClick;

public class MemCardBeforeSendDelegate extends AtmosDelegate {

    private MemGetCardEntity mData;
    private String cardStatus;
    private boolean isReadNow = false;
    private char mCardTag = 0x04;
    private String mReadCardNum;
    private String mCardStatus;

    @BindView(R2.id.tv_read_card)
    AppCompatTextView tvReadCard;
    @BindView(R2.id.tv_send_new_card)
    AppCompatTextView tvSendNewCard;
    @BindView(R2.id.tv_back_card)
    AppCompatTextView tvBackCard;

    @BindView(R2.id.tv_card_info)
    AppCompatTextView tvCardInfo;

    @OnClick(R2.id.tv_read_card)
    void onReadCard() {
        if (!isReadNow) {
            CardReadUtil.StartGetCardNum(getContext(), mCardTag, new CardReadEvent(new Bundle()));
            isReadNow = true;
        }
    }

    @OnClick(R2.id.tv_send_new_card)
    void onSendNewCard() {
        if (mData != null) {
            setNewCard(mData.getIcNo());
        }
    }

    @OnClick(R2.id.tv_back_card)
    void onBackCard() {
        if (mData != null) {
            setBackCard(mData.getIcNo());
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_mem_card_before_send;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(CardReadEvent event) {
        if (event != null && event.getData() != null) {
            showShortToast("读卡成功");
            isReadNow = false;
            if (StringUtil.isNotEmpty(event.getData().getString("cardNum"))) {
                mReadCardNum = event.getData().getString("cardNum");
                mCardStatus = event.getData().getString("cardStatus");
                if (mReadCardNum != null && mReadCardNum.contains("认证失败")) {
//                    setNewCard("");
                } else {
                    if (mCardStatus.equals("1")) {
                        showShortToast(mReadCardNum);
                        getCardInfo(mReadCardNum.substring(0, 18));
                    }
                }
            } else {
                showShortToast("这个卡是空的");
            }

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(CardWriteEvent event) {
        if (event != null && event.getData() != null) {
            showLongToast("写卡成功");
            isReadNow = false;
            showShortToast(event.getData().getString("cardNum"));
        }
    }

    private void getCardInfo(String cardNum) {

        WeakHashMap<String, Object> params = new WeakHashMap<>();
        params.put("deptId", FustionManager.mMachineData.getDeptId());
        params.put("icNo", cardNum);

        HttpHelper.RestClientGet(params, HttpUrl.GET_CARD_INFO,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        Type type = new TypeToken<MemGetCardEntity>() {
                        }.getType();
                        Gson gson = new Gson();
                        mData = gson.fromJson(response, type);

                        if (mData.getIcStatus() == 0) {
                            cardStatus = "发新卡";
                        } else if (mData.getIcStatus() == 1) {
                            cardStatus = "正常";
                        } else if (mData.getIcStatus() == 2) {
                            cardStatus = "暂停使用";
                        } else if (mData.getIcStatus() == 3) {
                            cardStatus = "锁卡";
                        } else if (mData.getIcStatus() == 4) {
                            cardStatus = "已换卡";
                        } else if (mData.getIcStatus() == 5) {
                            cardStatus = "已作废";
                        }
                        tvCardInfo.setText(String.format(getString(R.string.mem_card_get_info), String.valueOf(mData.getIcNo()), cardStatus));
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        if (msg.equals("CARD NOT EXISTS")) {
                            setNewCard("");
                        }
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {

                    }
                });

    }

    private void setNewCard(String cardNum) {

        WeakHashMap<String, Object> params = new WeakHashMap<>();
        params.put("deptId", FustionManager.mMachineData.getDeptId());
        params.put("icNo", cardNum);

        HttpHelper.RestClientPost(params, HttpUrl.NEW_CARD,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        Type type = new TypeToken<MemSendCardEntity>() {
                        }.getType();
                        Gson gson = new Gson();
                        MemSendCardEntity mData = gson.fromJson(response, type);

                        if (StringUtil.isNotEmpty(mData.getEnIcNo())) {
                            if (!isReadNow) {
                                isReadNow = true;
                                CardReadUtil.StartWriteCardNum(getContext(), mData.getEnIcNo() + "00000000000000", mCardTag, new CardReadEvent(new Bundle()));
                            }
                        }

                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        showShortToast(msg);
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {

                    }
                });

    }

    private void setBackCard(String cardNum) {

        WeakHashMap<String, Object> params = new WeakHashMap<>();
        params.put("deptId", FustionManager.mMachineData.getDeptId());
        params.put("icNo", cardNum);

        HttpHelper.RestClientPost(params, HttpUrl.BACK_CARD,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {

                        showShortToast("回收成功");
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        showShortToast(msg);
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {

                    }
                });

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }
}
